<template>
    <div class="page-title">
      <h2>生产补料</h2>
    </div>

  <div>
    <el-form :model="returnForm" ref="formRef" label-width="120px">
      <el-form-item label="单据主题" prop="documentSubject">
        <el-input v-model="returnForm.documentSubject"></el-input>
      </el-form-item>
      <el-form-item label="单据编号" prop="documentNo">
        <el-input v-model="returnForm.documentNo" disabled></el-input>
      </el-form-item>
      <el-form-item label="退料日期" prop="returnDate">
        <el-date-picker
          v-model="returnForm.returnDate"
          type="date"
          placeholder="选择退料日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="制单人员" prop="creator">
        <el-input v-model="returnForm.creator" disabled></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="returnForm.remarks"></el-input>
      </el-form-item>
      <el-form-item label="退料明细">
        <el-row>
          <el-col>
            <el-button @click="addRow" type="primary" size="small">增行</el-button>
            <el-button @click="copyRow" type="default" size="small">复制行</el-button>
            <el-button @click="deleteRow" type="danger" size="small">删行</el-button>
            <el-button @click="importData" type="success" size="small">导入</el-button>
            <el-button @click="importTemplate" type="info" size="small">导入模板</el-button>
          </el-col>
        </el-row>
        <el-table :data="returnDetailsList" stripe>
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="index" label="序号"></el-table-column>
          <el-table-column prop="productName" label="产品名称" required></el-table-column>
          <el-table-column prop="productCode" label="产品编号"></el-table-column>
          <el-table-column prop="specificationModel" label="规格型号"></el-table-column>
          <el-table-column prop="unit" label="单位"></el-table-column>
          <el-table-column prop="returnQuantity" label="本次退料数量" required>
            <template #default="{ row }">
              <el-input v-model="row.returnQuantity" type="number"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="returnableQuantity" label="可退料数量">
            <template #default="{ row }">
              <el-input v-model="row.returnableQuantity" type="number"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="returnReason" label="退料原因">
            <template #default="{ row }">
              <el-input v-model="row.returnReason"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="batchNumber" label="批号">
            <template #default="{ row }">
              <el-input v-model="row.batchNumber"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="productionDate" label="生产日期">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.productionDate"
                type="date"
                placeholder="选择生产日期"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="expiryDate" label="有效日期">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.expiryDate"
                type="date"
                placeholder="选择有效日期"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="warehouse" label="出库仓库">
            <template #default="{ row }">
              <el-input v-model="row.warehouse"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="relatedSubject" label="关联领料/补料主题">
            <template #default="{ row }">
              <el-input v-model="row.relatedSubject"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="relatedProject" label="关联项目">
            <template #default="{ row }">
              <el-input v-model="row.relatedProject"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="退料数量合计">
          <el-input v-model="totalReturnQuantity" disabled></el-input>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button @click="submitForm" type="primary">提交</el-button>
        <el-button @click="resetForm" type="default">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';

// 假设当前用户信息存在，这里简单模拟
const currentUser = ref({ name: 'admin' });

// 主表单数据
const returnForm = reactive({
  documentSubject: '',
  documentNo: '',
  returnDate: null,
  creator: currentUser.value.name,
  remarks: ''
});

// 退料明细列表
const returnDetailsList = ref([]);
// 退料数量合计
const totalReturnQuantity = ref(0);

// 增行
const addRow = () => {
  const newRow = {
    index: returnDetailsList.value.length + 1,
    productName: '',
    productCode: '',
    specificationModel: '',
    unit: '',
    returnQuantity: 0,
    returnableQuantity: 0,
    returnReason: '',
    batchNumber: '',
    productionDate: null,
    expiryDate: null,
    warehouse: '',
    relatedSubject: '',
    relatedProject: ''
  };
  returnDetailsList.value.push(newRow);
  nextTick(() => {
    calculateTotal();
  });
};

// 复制行
const copyRow = () => {
  const selectedRows = returnDetailsList.value.filter(row => row._isSelected);
  if (selectedRows.length > 0) {
    const newRows = selectedRows.map(row => ({...row, index: returnDetailsList.value.length + 1 }));
    returnDetailsList.value.push(...newRows);
    nextTick(() => {
      calculateTotal();
    });
  } else {
    ElMessage.warning('请先选择要复制的行');
  }
};

// 删行
const deleteRow = () => {
  const selectedRows = returnDetailsList.value.filter(row => row._isSelected);
  if (selectedRows.length > 0) {
    returnDetailsList.value = returnDetailsList.value.filter(row =>!row._isSelected);
    nextTick(() => {
      calculateTotal();
    });
  } else {
    ElMessage.warning('请先选择要删除的行');
  }
};

// 计算退料数量合计
const calculateTotal = () => {
  const sum = returnDetailsList.value.reduce((acc, row) => acc + row.returnQuantity, 0);
  totalReturnQuantity.value = sum;
};

// 导入数据（这里只是占位，实际需实现导入逻辑）
const importData = () => {
  ElMessage.info('导入功能暂未实现');
};

// 导入模板（这里只是占位，实际需实现导入模板逻辑）
const importTemplate = () => {
  ElMessage.info('导入模板功能暂未实现');
};

// 提交表单
const submitForm = async () => {
  const formRef = ref(null);
  await formRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
       ...returnForm,
        details: returnDetailsList.value
      };
      // 这里模拟发送数据到后端，实际使用时替换为真实接口请求
      console.log('提交的数据:', submitData);
      ElMessage.success('提交成功');
    } else {
      ElMessage.error('表单校验不通过，请检查输入');
    }
  });
};

// 重置表单
const resetForm = () => {
  returnForm.documentSubject = '';
  returnForm.returnDate = null;
  returnForm.remarks = '';
  returnDetailsList.value = [];
  totalReturnQuantity.value = 0;
};
</script>

<style scoped>
.page-title {
    text-align: center;
}
</style>